package hu.tortavar2.server;

import java.util.ArrayList;
import java.util.List;

import hu.tortavar2.shared.ProductCategory;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.SortDirection;

public class ProductCategoryDao {

	DatastoreService datastore;
	
	public ProductCategoryDao() {
		datastore = DatastoreServiceFactory.getDatastoreService();
	}

	public List<ProductCategory> getRecentCategory() {
		Query query = new Query("ProductCategory");
		query.addSort(ProductCategory.PRODUCT_CATEGORY_SHORT_NAME, SortDirection.ASCENDING);
		
		ArrayList<ProductCategory> results = new ArrayList<ProductCategory>();
		for (Entity result : datastore.prepare(query).asIterable()) {
			ProductCategory category = fromEntity(result);
			results.add(category);
		}
		return results;
	}
	
	public void deleteCategory(String encodedKey) {
		Key key = KeyFactory.stringToKey(encodedKey);
		datastore.delete(key);
	}
	
	//Kategória hozzáadása
	public String addProductCategory(ProductCategory category) {
		Entity entity = new Entity(ProductCategory.PRODUCT_CATEGORY_ENTITY_NAME);
		entity.setProperty(ProductCategory.PRODUCT_CATEGORY_LONG_NAME, category.getCategoryLongName());
		datastore.put(entity);
		//itt ez nem biztos, h jó...
		String encodedKey = KeyFactory.keyToString(entity.getKey());
		return encodedKey;
	}
	
	private ProductCategory fromEntity(Entity result) {
		ProductCategory category = new ProductCategory();
		category.setCategoryLongName((String)result.getProperty(ProductCategory.PRODUCT_CATEGORY_LONG_NAME));
		category.setCategoryShortName((String)result.getProperty(ProductCategory.PRODUCT_CATEGORY_SHORT_NAME));
		
		if(category.getKey() == null) {
			String encodedKey = KeyFactory.keyToString(result.getKey());
			category.setKey(encodedKey);
		}
		return category;
	}
}
